package ar.com.agea.util


import groovyx.net.http.ContentType
import groovyx.net.http.EncoderRegistry
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import ar.com.agea.exception.ApplicationException

class ExternalApiHandler {

	private static final Logger log = LoggerFactory.getLogger(ExternalApiHandler.class)
		
	protected createHTTPBuilder(String url) {
		HTTPBuilder http = new HTTPBuilder("${url}")
		http.encoderRegistry = new EncoderRegistry(charset: 'utf-8')
		return http
	}
	
	protected doRequest(String url, String path, Method method, ContentType contentType, Closure successClosure) {
		doRequest(url + path, method, contentType, null, successClosure)
	}
	
	protected doRequest(String url, String path, Method method, Map headers, ContentType contentType, Closure successClosure) {
		doRequest(url + path, method, headers, contentType, null, successClosure)
	}
	
	protected doRequest(String url, Method method, ContentType contentType, Closure successClosure) {
		doRequest(url, method, contentType, null, successClosure)
	}
	
	protected doRequest(String url, Method method, Map headersMap, ContentType contentType, String bodyContent, Closure successClosure) {
		executeRequest(url, method, contentType) { req ->
			if (bodyContent) {
				body = bodyContent
			}
			
			if (headersMap) {
				headers = headersMap
			}

			handleFailure(response, url, bodyContent)
			response.success = successClosure
		}
	}
	
	protected doRequest(String url, Method method, ContentType contentType, String bodyContent, Closure successClosure) {
		executeRequest(url, method, contentType) { req ->
			if (bodyContent) {
				body = bodyContent
			}

			handleFailure(response, url, bodyContent)
			response.success = successClosure
		}
	}
	
	protected executeRequest(String url, Method method, ContentType contentType = null, Closure requestClosure) {
		try {
			def http = this.createHTTPBuilder(url)
			println ("Executing request to: ${method.toString()} - ${url}")
			if (contentType) {
				http.request(method, contentType, requestClosure)
			} else {
				http.request(method, requestClosure)
			}
		}
		  catch(Exception e) {
			throw new ApplicationException("Error executing the request", e)
		}
	}
	
	protected handleFailure(def resp, def uri, def body) {
		resp.failure = { r ->
			throw new ApplicationException("Unexpected error invoking (${uri}) with content (${body}). Status Code: [${r.statusLine.statusCode}], reason: [${r.statusLine.reasonPhrase}]")
		}
	}
	
}
